#include "usettingsitem.h"
#include "uapplication.h"
#include "style/upalette.h"
#include "style/uproxystyle.h"
#include "style/ustylepainter.h"

#include <QVBoxLayout>

class USettingsItemPrivate
{
public:
    USettingsItemPrivate(USettingsItem* q) : q_ptr(q) {}
    ~USettingsItemPrivate() {}

private:
    Q_DECLARE_PUBLIC(USettingsItem)
    Q_DISABLE_COPY(USettingsItemPrivate)
    USettingsItem* const q_ptr = nullptr;

    QHBoxLayout *mainLayout = nullptr;
    QSize iconSize = QSize(20, 20);
    QString text = "";
    QIcon icon = QIcon();
    QStyleOptionViewItem::ViewItemPosition viewItemPosition;
};

USettingsItem::USettingsItem(QWidget* parent) : QWidget(parent)
    , d_ptr(new USettingsItemPrivate(this))
{
    Q_D(USettingsItem);
    d->mainLayout = new QHBoxLayout;
    setLayout(d->mainLayout);
}

USettingsItem::~USettingsItem()
{
}

void USettingsItem::setItemPosition(const QStyleOptionViewItem::ViewItemPosition position)
{
    Q_D(USettingsItem);
    if (d->viewItemPosition != position)
    {
        d->viewItemPosition = position;
        update();
    }
}

void USettingsItem::setIcon(const QIcon &icon)
{
    Q_D(USettingsItem);
    d->icon = icon;
    update();
}

QIcon USettingsItem::icon()
{
    Q_D(USettingsItem);
    return d->icon;
}

void USettingsItem::setIconSize(const QSize &size)
{
    Q_D(USettingsItem);
    if (d->iconSize != size)
    {
        d->iconSize = size;
        update();
    }
}

QSize USettingsItem::iconSize() const
{
    Q_D(const USettingsItem);
    return d->iconSize;
}

void USettingsItem::setText(const QString &text)
{
    Q_D(USettingsItem);
    if (d->text != text)
    {
        d->text = text;
        update();
    }
}

QString USettingsItem::text() const
{
    Q_D(const USettingsItem);
    return d->text;
}

void USettingsItem::addWidget(QWidget *widget, Qt::Alignment alignment)
{
    Q_D(USettingsItem);
    d->mainLayout->addWidget(widget, 0, alignment);
}

void USettingsItem::initStyleOption(USettingsItemStyleOption* option) const
{
    Q_D(const USettingsItem);
    option->initFrom(this);
    option->viewItemPosition = d->viewItemPosition;
    option->icon = d->icon;
    option->iconSize = d->iconSize;
    option->backgroundColor = uApp->applicationPalette()->color(UProxyStyle::colorGroup(option, this), UPalette::ItemBackground);
    option->text = d->text;
}

void USettingsItem::paintEvent(QPaintEvent*)
{
    UStylePainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);

    USettingsItemStyleOption opt;
    initStyleOption(&opt);

    qreal opacity = isEnabled() ? 1.0 : 0.4;
    painter.setOpacity(opacity);
    painter.drawPrimitive(UProxyStyle::PE_SettingsItem, opt);
}

